/*
 * Copyright (C) 2008-2011 CBDP Consortium
 * 
 * All rights reserved.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution.
 * 
 * This software consists of contributions made by many individuals, 
 * listed below:
 *
 * Author: 	Xabier Laiseca <xabier.laiseca@deusto.es>
 * 			David Ausín <david.ausin@deusto.es>
 */
package cbdp.server.contextreasoner.impl.contextmanager.online.model;

import static cbdp.server.contextreasoner.impl.contextmanager.online.model.Checker.*;
import cbdp.server.contextreasoner.model.Instance;
import cbdp.server.contextreasoner.model.ObjectDatatypeProperty;
import cbdp.server.contextreasoner.model.exceptions.NotExistingInstanceException;

import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.shared.Lock;

public class EagerSavingObjectDatatypeProperty extends EagerSavingGenericProperty implements ObjectDatatypeProperty
{
	private Individual individual;
	
	@Override
	public void setStatement(final Statement statement)
	{
		super.setStatement(statement);
		
		this.individual = statement.getObject().as(Individual.class);
	}

	@Override
	public String getId()
	{
		return individual.getURI();
	}

	@Override
	public Instance getObject()
	{
		final EagerSavingInstance instance = new EagerSavingInstance();
		instance.setOntModel(ontModel);
		instance.setIndividual(individual);
		
		return instance;
	}
	
	@Override
	public void setObject(final String objectName) throws NotExistingInstanceException
	{
		checkNullParameter(objectName, "objectName");
		
		ontModel.enterCriticalSection(Lock.WRITE);
		
		try
		{
			final Individual individual = ontModel.getIndividual(objectName);
			
			if(individual != null)
			{
				throw new NotExistingInstanceException("The instance " + objectName +" does not exist");
			}
			
			statement.changeObject(individual);
		}
		finally
		{
			ontModel.leaveCriticalSection();
		}
	}

	@Override
	public void notifyDeleted()
	{	
		individual = null;
	}
	
}
